#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author  : 邢建辉
# @Email   : xjh_0125@sina.com
# @Time    : 2022/1/21 14:26
# @Software: PyCharm
# @File    : e-learing.py


# !/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime
import random
import re
import time
import threading

import requests
from lxml import etree


class CourseModel:
    def __init__(self, CourseId, TrainId):
        self.TrainId = TrainId
        self.CourseId = CourseId
        self.Items = []
        self.resID = ''

    def __str__(self):
        return self.TrainId + '----' + self.CourseId + '-----' + str(self.Items) + '--------' + self.resID


class myThread(threading.Thread):
    def __init__(self, func, thread_id, course, item_id):
        threading.Thread.__init__(self)
        self.threadID = thread_id
        self.course = course
        self.item_id = item_id
        self.func = func

    def run(self):
        print("开始线程：" + self.threadID)
        self.func(self.course, self.item_id)
        print("退出线程：" + self.threadID)


class ELearingCrawler:

    def __init__(self, shop_id, cookies, delay=7):
        self.shop_id = shop_id
        self._delay = delay
        self.font_dict = {}
        self._cookies = self._format_cookies(cookies)
        self._css_headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',
        }
        self._default_headers = {
            'Connection': 'keep-alive',
            'Host': 'elearning.tcsasac.com',
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',
            'Sec-Fetch-Dest': 'document',
            'Sec-Fetch-Mode': 'navigate',
            'Sec-Fetch-Site': 'none',
            'Sec-Fetch-User': '?1',
            'Upgrade-Insecure-Requests': '1'
        }
        # https://elearning.tcsasac.com/Study/Train/211126600000861
        self._cur_request_url = 'https://elearning.tcsasac.com/Study/Train/{}'.format(shop_id)

    def _delay_func(self):
        delay_time = random.randint((self._delay - 2) * 10, (self._delay + 2) * 10) * 0.1
        print('睡一会', delay_time)
        time.sleep(delay_time)

    def _format_cookies(self, cookies):
        cookies = {cookie.split('=')[0]: cookie.split('=')[1]
                   for cookie in cookies.replace(' ', '').split(';')}
        return cookies

    def _get_course_list(self):
        res = requests.get(self._cur_request_url, headers=self._default_headers, cookies=self._cookies)
        html = res.text
        course_list_res = re.findall(r'<a href="/Study/Course/(.*?)\?TrainId=(.*?)"><span class="name">', html)
        course_list = []
        for c in course_list_res:
            course_list.append(CourseModel(c[0], c[1]))
        for c in course_list:
            self._get_course_item(c)
            # if c.CourseId == '211215400000625' or c.CourseId == '211123400000968':
            #     pass
            #     #已经学过的课程跳过
        threads = []
        for c in course_list:
            for item in c.Items:
                threads.append(myThread(self._set_time, item, c, item))
        for t in threads:
            t.start()
        for t in threads:
            t.join()
        print('任务结束')

    def _get_course_item(self, course: CourseModel):
        course_item_url = 'https://elearning.tcsasac.com/Study/Course/{}?TrainId={}'.format(course.CourseId,
                                                                                            course.TrainId)

        res = requests.get(course_item_url, headers=self._default_headers, cookies=self._cookies)
        html = res.text
        course.Items = re.findall(r'<a href="/Study/Play/(.*?)\?CourseId=', html)
        for item in course.Items:
            self._get_video_detail(course, item)

    def _get_video_detail(self, course: CourseModel, itemId):
        video_url = 'https://elearning.tcsasac.com/Study/Play/{}?CourseId={}&TrainId={}'.format(itemId, course.CourseId,
                                                                                                course.TrainId)
        res = requests.get(video_url, headers=self._default_headers, cookies=self._cookies)
        html = res.text
        res_id = re.search(r'resID:(.*?),', html)
        if res_id is not None:
            course.resID = res_id.group(1)

    def _set_time(self, course: CourseModel, itemId):
        # {
        #     "success": true,
        #     "code": 200,
        #     "count": 0,
        #     "data": null,
        #     "msg": "ok"
        # }
        if itemId == '211126600000861' or itemId == '211215410000604':
            return
        timepoint = 0
        while True:
            timepoint += 20
            set_recore_url = 'https://elearning.tcsasac.com/User/SetRecord?cid={}&wid={}&tid={}&resID={}&timepoint={}&key=123'.format(
                course.CourseId, itemId, course.TrainId, course.resID, timepoint + round(random.random(), 3))
            res = requests.get(set_recore_url, headers=self._default_headers, cookies=self._cookies)
            json = res.json()
            print(json, set_recore_url)
            if json['code'] != 200 and timepoint > 1000:
                break
            # self._delay = 1
            self._delay_func()

    def run(self):
        self._get_course_list()
        # threads = []
        # for i in range(5):
        #     t = myThread(self.print_time, i, 'Thread-{}'.format(i), 5)
        #     threads.append(t)
        # for t in threads:
        #     t.start()
        # for t in threads:
        #     t.join()
        # print('end')

    def print_time(self, thread_name, delay):
        count = 0
        while count < 5:
            time.sleep(delay)
            count += 1
            print("%s: %s" % (thread_name, time.ctime(time.time())))


if __name__ == "__main__":
    COOKIES = 'Hm_lvt_a69d96593f36eb8898e75d771d343875=1642642991,1642737264,1643118702,1643157506; .AspNetCore.Antiforgery.o22_7h5v7N0=CfDJ8PQRCC-RczZNqjDbpCH9otw0e77B700ScfKlk4ddmf6DC0uoDgpqSbxC5T5nYsj2ibzHKRTxHJq0aV3c584FsDGzaSdiJrrCdJo_Mtqm1TyzR2OmG-QG-UPc7u9J91o31SsnNvTNOiBGAq1r6Ox8xqI; .AspNetCore.Cookies=CfDJ8CQDldBakoJOmqcGbKz5_53L5wV45ehYSUTeNZpe66M1Eb111TiSAOV00hKH0YhLU_zTVKpMabQzf96RlFr2o5GZfvcjWre-jsLz5Q_P58KkGVRLVGsX_ShH4au9onFTyUgKCnO2DgTd8gTJQtvKHPS0CeplQE0KMjTsPbUo0Grv1rZwVhR70Gc9LIzauH7bMg4k9gSyd_DGh28M6eWffhqZdfNKIyro0b6WUNMpj5M-oDL_sdNQetr1RIuse8W8y8xZO8Ym9eqCc6z0aS8EsvdCs3wixNRxVZ8nrZ7mdCJlI7HcaQs6ml6UlSWbHPuhsv-IDfVXadMmmotpkkhDmV9XAE5zPQX0ijQHpdpG8pfg_HkyWGdutAKrbrk6-uQHAt0T0nkdCWDADTHF-3wlKV1tzayN-Bc_Z7OjOTBZuqcQd7lwxugWCmrI0yK79mnrfnWxL6tNZ7haoh81IMe5GcR_ad1T6X9s4U2UMagKMVkJrsiw5Zzn3zYQs-Wj1SwX20OzyaTGvcZ9ge4DKDeO8jVaFi_ycEHQcBRPfxRItppt; Hm_lpvt_a69d96593f36eb8898e75d771d343875=1643157708'
    dp = ELearingCrawler('211126600000861', cookies=COOKIES, delay=20)
    dp.run()

    # c = CourseModel('123', '232')
    # c.Items = ['123', '2323']
    # c.resID = '1232'
    # print(c)
